package com.foreveross.mofang.serviceconsole.web.controller.common;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.openkoala.koala.auth.core.domain.User;
import org.openkoala.koala.auth.ss3adapter.AuthUserUtil;
import org.openkoala.koala.auth.ss3adapter.CustomUserDetails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 控制层基础类
 * 
 * @author fb
 */
@Controller
public abstract class BaseController {

	protected final Logger log = LoggerFactory.getLogger(this.getClass());

	protected static final String LOGIN_USER = "login_user";

	@ResponseBody
	@ExceptionHandler({ RuntimeException.class, Exception.class })
	protected Map<String, Object> runtimeExceptionHandler(Throwable e) {
		log.error("系统异常：", e);

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("error", ExceptionMsg.getMsg(e));
		return result; 
	}

	protected User getLogionUser() {
		if (session.getAttribute(LOGIN_USER) == null) {
			synchronized (BaseController.class) {
				if (session.getAttribute(LOGIN_USER) == null) {
					CustomUserDetails cud = AuthUserUtil.getLoginUser();
					List<User> user = User
							.getRepository()
							.createJpqlQuery("select user from User user where user.userAccount=:userAccount")
							.addParameter("userAccount", cud.getUsername()).list();
					
					if (user.isEmpty()) {
						log.warn("用户{}在数据库中不存在，可能为配制用户!");
					}
					
					session.setAttribute(LOGIN_USER, user.get(0));
				}
			}
		}

		return (User) session.getAttribute(LOGIN_USER);
	}

	protected enum ExceptionMsg {
		// spring mvc v层jsr303数据验证的规范校验
		BINDEXCEPTION {

			@Override
			protected void setMsg(Throwable e) {
				if (e instanceof BindException) {
					FieldError fe = ((BindException) e).getBindingResult().getFieldError();
					m = p.matcher(fe.getDefaultMessage() == null ? "" : fe.getDefaultMessage());

					if (m.find()) {
						errorMessage = fe.getDefaultMessage();
					}
				} else {
					CONSTRAINTVIOLATIONEXCETIPN.setMsg(e);
				}
			}

		},

		// domain层jsr303数据验证的规范校验
		CONSTRAINTVIOLATIONEXCETIPN {

			@Override
			protected void setMsg(Throwable e) {
				if (e instanceof ConstraintViolationException) {
					ConstraintViolationException cve = (ConstraintViolationException) e;
					Set<ConstraintViolation<?>> setCv = cve.getConstraintViolations();

					if (!setCv.isEmpty()) {
						ConstraintViolation<?> cv = (ConstraintViolation<?>) setCv.toArray()[0];
						m = p.matcher(cv.getMessage() == null ? "" : cv.getMessage());

						if (m.find()) {
							errorMessage = cv.getMessage();
						}
					}
				} else {
					DEFAULT.setMsg(e);
				}
			}
		},

		DEFAULT {

			@Override
			protected void setMsg(Throwable e) {
				m = p.matcher(e.getMessage() == null ? "" : e.getMessage());

				if (m.find()) {
					errorMessage = e.getMessage();
				}
			}
		};

		private static Pattern p = Pattern.compile("[\u4e00-\u9fa5]{1,}");
		private static String errorMessage = "系统异常!";
		private static Matcher m = null;

		protected abstract void setMsg(Throwable e);

		public static String getMsg(Throwable e) {
			errorMessage = "系统异常!";
			BINDEXCEPTION.setMsg(e);

			return errorMessage;
		}
	}

	@Inject
	protected HttpSession session;
}
